package com.zprmb.udzt.fragment;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONObject;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.zprmb.udzt.DexterityPayInActivity;
import com.zprmb.udzt.Log_or_RegisActivity;
import com.zprmb.udzt.LoginActivity;
import com.zprmb.udzt.ProductDetailsJiluActivity;
import com.zprmb.udzt.R;
import com.zprmb.udzt.V4WebViewActivity;
import com.zprmb.udzt.util.Constant;
import com.zprmb.udzt.util.ToastUtil;
import com.zprmb.udzt.util.VolleryUtil;
import com.zprmb.udzt.view.RulerView;
import com.zprmb.udzt.view.RulerView.OnScaleListener;
import com.zprmb.udzt.view.WaveHelper;
import com.zprmb.udzt.view.WaveView;

public class DexterityFragment extends Fragment implements OnClickListener,OnRefreshListener2<ScrollView>{
	private RulerView rulerView;
	private PullToRefreshScrollView sv;
	private ImageView iv_v4_nonetwork;

	private EditText et_amount;
	private TextView tv_every_day,tv_year,rate_of_return;
	private Handler handler;
	DecimalFormat df = new DecimalFormat("###0.0000");  
	DecimalFormat df2 = new DecimalFormat("###0.00");  
	private TextView tv_name,tv_no,tv_remain,tv_investnum,tv_desc;
	private Button feature1,feature2,feature3,btn_in;
	private List<String> list=new ArrayList<String>();
	private Double millionAccrua=(double) 0,rate=(double) 0;
	private RelativeLayout rl_detail,rl_invest_help,rl_invest_record,rl_activity;
	private String id,url,desc="";
	private boolean islogin=false,flag;
	private SharedPreferences sha;
	private int remainAmount;
	private WaveView wv;
	private WaveHelper helper;
	
	@Override
	@Nullable
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view=inflater.inflate(R.layout.lingcunbao, null);
		rulerView=(RulerView)view.findViewById(R.id.ruler_view);
		rulerView.setGravity(Gravity.BOTTOM);
		sv=(PullToRefreshScrollView)view.findViewById(R.id.sv);
		sha=getActivity().getSharedPreferences("config", getActivity().MODE_PRIVATE);
		et_amount=(EditText)view.findViewById(R.id.invest_amount);
		tv_every_day=(TextView)view.findViewById(R.id.tv_accumulated_earnings);
		tv_year=(TextView)view.findViewById(R.id.available_Balance);
		rate_of_return=(TextView)view.findViewById(R.id.rate_of_return); 
		tv_name=(TextView)view.findViewById(R.id.product_name);
		feature1=(Button)view.findViewById(R.id.feature1);
		feature2=(Button)view.findViewById(R.id.feature2);
		feature3=(Button)view.findViewById(R.id.feature3);
		tv_no=(TextView)view.findViewById(R.id.product_no);
		btn_in=(Button)view.findViewById(R.id.btn_in);
		iv_v4_nonetwork=(ImageView)view.findViewById(R.id.iv_v4_nonetwork);
		tv_remain=(TextView)view.findViewById(R.id.tv_remain);
		rl_detail=(RelativeLayout)view.findViewById(R.id.detail);
		rl_invest_help=(RelativeLayout)view.findViewById(R.id.rl_invest_help);
		rl_invest_record=(RelativeLayout)view.findViewById(R.id.rl_invest_record);
		tv_investnum=(TextView)view.findViewById(R.id.tv_investnum);
		rl_activity=(RelativeLayout)view.findViewById(R.id.rl_activity);
		tv_desc=(TextView)view.findViewById(R.id.tv_desc);
		wv=(WaveView)view.findViewById(R.id.product_wave);
		helper=new WaveHelper(wv);
		helper.start();
		rulerView.setIndicatePadding(10);
		sv.setOnRefreshListener(this);
		rl_activity.setOnClickListener(this);
		btn_in.setOnClickListener(this);
		rl_detail.setOnClickListener(this);
		rl_invest_help.setOnClickListener(this);
		rl_invest_record.setOnClickListener(this);
		
				iv_v4_nonetwork.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						initData(true);
					}
				});
		
		rulerView.post(new Runnable() {
            @Override
            public void run() {
               
                rulerView.smoothScrollTo(1);
            }
        });
		rulerView.setOnScaleListener(new OnScaleListener() {
			
			@Override
			public void onScaleChanged(int scale) {
				// TODO Auto-generated method stub
		 Log.e("tag", scale+"");
		 et_amount.setText(scale*100+"");
		if(scale<1){
			rulerView.smoothScrollTo(1); 
		}
		
		tv_every_day.setText(df.format((scale*100)*millionAccrua/10000)+"");
		tv_year.setText(df2.format((scale*100)*rate/100)+"");
			}
		});
		handler = new Handler();  
		
		et_amount.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Runnable runnable=new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						sv.scrollTo(0, 200);
						
					}
				};
				handler.postDelayed(runnable, 200);  
			}
			
		});
		initData(true);
		
		return view;
	}
	
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		initData(false);
		userinfo();
	}
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if(helper!=null){
			helper.cancel();
		}
	}
	private void initData( boolean show) {
		// TODO Auto-generated method stub
		VolleryUtil volleryUtil=new VolleryUtil() {
			
			@Override
			public void onUpDate(JSONObject jsonObject) {
				// TODO Auto-generated method stub
				Log.e("Dexterity", jsonObject.toString());
				if(jsonObject.optInt("success")==1){
					sv.setVisibility(View.VISIBLE);
					btn_in.setVisibility(View.VISIBLE);
					iv_v4_nonetwork.setVisibility(View.GONE);
					JSONObject json1=jsonObject.optJSONObject("data");	
					JSONObject json2=json1.optJSONObject("activityDesc");		
					Gson gson=new Gson();
					list=gson.fromJson(json1.optString("characterList"), new TypeToken<ArrayList<String>>() {
					}.getType());
					if(json1.optString("status").equals("FINISHED")){
						btn_in.setBackgroundResource(R.drawable.btn_unclick);
						btn_in.setText("已售罄");
					}else{
						btn_in.setBackgroundResource(R.drawable.my_button);
						btn_in.setText("马上转入");
					}
						if(list.size()>=3){
							
							feature1.setText(list.get(0));
							feature2.setText(list.get(1));
							feature3.setText(list.get(2));
						}
					
					rate_of_return.setText(json1.optString("rate")+"%");
					remainAmount=json1.optInt("remainAmount");
					tv_remain.setText(df2.format(Double.parseDouble(json1.optString("remainAmount"))));
					millionAccrua=json1.optDouble("millionAccrual");
					rate=json1.optDouble("rate");
					tv_name.setText(json1.optString("productName"));
					tv_no.setText(json1.optString("productNo"));
					tv_investnum.setText(json1.optString("investCount")); 
					if(json2!=null){
						url=json1.optString("url");
						desc=json1.optString("desc");
						tv_desc.setText(json1.optString("desc"));
					}
					id=json1.optString("productId");
					flag=json1.optBoolean("flagFresh");
					if(desc.length()<=0){
						rl_activity.setVisibility(View.GONE);
					}else{
						rl_activity.setVisibility(View.VISIBLE);
					}
							
				}
				
			}
			  
			@Override
			public void onError() {
				// TODO Auto-generated method stub
				sv.setVisibility(View.GONE);
				btn_in.setVisibility(View.GONE);
				iv_v4_nonetwork.setVisibility(View.VISIBLE);
				
			}
		};
		volleryUtil.setRequestMethod(0);
		volleryUtil.setShow(show);
		volleryUtil.execute(getActivity(), Constant.URL+"/api/v5/list/currentDeposit", "");
		}

	public static DexterityFragment newInstance(int position, String string) {
		DexterityFragment uf = new DexterityFragment();

		return uf;
	}
	private void userinfo(){
	VolleryUtil volleryUtil=new VolleryUtil() {
		
		@Override
		public void onUpDate(JSONObject jsonObject) {
			// TODO Auto-generated method stub
			if (jsonObject.optInt("success")==1) {
				JSONObject json = jsonObject.optJSONObject("data");
				
				islogin=true;
			}else {
				if (jsonObject.optString("comment").equals("please login")) {
					islogin=false;
				}else {
					ToastUtil.showCenterToast(getActivity(), jsonObject.optString("comment"));
				}
			}
			
		}
		
		@Override
		public void onError() {
			// TODO Auto-generated method stub
			
		}
	};
	volleryUtil.setHeaders("token", sha.getString("token", ""));
	volleryUtil.setRequestMethod(0);
	volleryUtil.execute(getActivity(), Constant.URL+"apiAccount/userInfo", "");
}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		case R.id.btn_in:
			if(islogin){
			Intent	intent=new Intent(getActivity(),DexterityPayInActivity.class);
		     intent.putExtra("id", id);
		     intent.putExtra("million", millionAccrua);
		     intent.putExtra("money", et_amount.getText().toString());
				startActivity(intent);
		}else{
			if(sha.getString("mobile", "").equals("")){
				Intent intent = new Intent(getActivity(),Log_or_RegisActivity.class);
				intent.putExtra("who", 4);
				startActivity(intent);
			}else{
				
				Intent intent = new Intent(getActivity(),LoginActivity.class);
				intent.putExtra("who", 3);
				startActivity(intent);
			}
		}
			break;
		case R.id.detail:
			Intent intent2=new Intent(getActivity(),V4WebViewActivity.class);
			intent2.putExtra("url", "/h5/knowCurrent?app=true");
			intent2.putExtra("title", "项目介绍 ");
			startActivity(intent2);
			break;
		case R.id.rl_invest_help:
			Intent intent5=new Intent(getActivity(),V4WebViewActivity.class);
			intent5.putExtra("url", "/h5/helpCurrent?app=true");
			intent5.putExtra("title", "项目帮助");
			startActivity(intent5);
			break;
		case R.id.rl_invest_record:
			Intent intent3=new Intent(getActivity(),ProductDetailsJiluActivity.class);
	    	intent3.putExtra("url", "/api/v5/product/uplanDetail/{productId}/invest");
	    	intent3.putExtra("id", id);
	    	intent3.putExtra("Dexter", 1);
	    	Log.e("liongcunid", id);
	    	intent3.putExtra("who", "uplan");
	    	intent3.putExtra("flagFresh", flag);
    	    startActivity(intent3);
			break;
		case R.id.rl_activity:
			Intent intent4=new Intent(getActivity(),V4WebViewActivity.class);
			intent4.putExtra("url", url+"?app=true");
	    	intent4.putExtra("title", desc);
	    	
    	startActivity(intent4);
			break;
			
		
		
		
		}
		
	}
	Handler handler2 = new Handler() {
		public void handleMessage(Message msg) {
			list.clear();
			initData(true);
//			Toast.makeText(getActivity(), "刷新成功", 2000).show();
			sv.onRefreshComplete();
		};
	};
	@Override
	public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
		// TODO Auto-generated method stub
		handler2.sendEmptyMessage(1);
	}
	@Override
	public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
		// TODO Auto-generated method stub
		
	}
}
